#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define MAX_BUF 1024
#define SERVER_IP "192.168.1.108"  // 修改为服务器实际IP
#define PORT 7575

int main() {
    int sockfd;
    struct sockaddr_in server_addr;
    char buffer[MAX_BUF];
    
    // 创建socket
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }
    
    // 配置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    
    // 转换IP地址
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
        perror("invalid address");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
    
    // 连接服务器
    if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("connection failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }
    
    printf("Connected to server at %s:%d\n", SERVER_IP, PORT);
    
    while(1) {
        printf("Enter message (type 'exit' to quit): ");
        fgets(buffer, MAX_BUF, stdin);
        
        // 移除换行符
        buffer[strcspn(buffer, "\n")] = 0;
        
        // 退出条件
        if (strcmp(buffer, "exit") == 0) {
            break;
        }
        
        // 发送数据
        if (send(sockfd, buffer, strlen(buffer), 0) == -1) {
            perror("send failed");
            break;
        }
        
        // 接收响应
        ssize_t bytes_received = recv(sockfd, buffer, MAX_BUF - 1, 0);
        if (bytes_received <= 0) {
            if (bytes_received == 0) {
                printf("Server disconnected\n");
            } else {
                perror("recv failed");
            }
            break;
        }
        
        buffer[bytes_received] = '\0';
        printf("Server response: %s\n", buffer);
    }
    
    close(sockfd);
    printf("Connection closed\n");
    return 0;
}
